package middleware

import (
	"encoding/json"
	"haiqiu-go-admin/config"
	"haiqiu-go-admin/result"
	"haiqiu-go-admin/utils"
	"net/http"
)

var urls = make([]string, 0)

// 授权验证
func Auth() Middleware {
	return func(handlerFunc http.HandlerFunc) http.HandlerFunc {
		return func(w http.ResponseWriter, r *http.Request) {
			//判断是否为OPTIONS请求，跨域请求，非跨域请求不会出现options请求，
			//自定义请求头，请求头中的content-type是application/x-www-form-urlencoded，multipart/form-data，text/plain之外的格式
			if r.Method == http.MethodOptions {
				Cors(w, r)
				return
			}
			path := loadAccept(w, r)
			//log.Println(urls)
			if len(urls) != 0 {
				for _, v := range urls {
					if v == path {
						//执行下一步中间件或业务处理
						handlerFunc(w, r)
						return
					}
				}
			}
			if !(utils.Token{}.VerifyToken(w, r)) {
				var res = result.Res{Code: 5002, Message: "用户帐户已过期"}
				result.Custom(w, r, &res)
				return
			}
			//执行下一步中间件或业务处理
			handlerFunc(w, r)
		}
	}
}

func loadAccept(w http.ResponseWriter, r *http.Request) string {
	path := r.URL.Path
	if len(urls) != 0 {
		//log.Println("已加载放行url地址")
		return path
	}
	//log.Println("首次加载放行url地址")
	// 获取配置文件的放行url地址
	acceptUrls := config.ViperConfig.Get("accept.urls")
	marshal, err := json.Marshal(acceptUrls)
	if err != nil {
		panic(err)
	}
	err = json.Unmarshal(marshal, &urls)
	if err != nil {
		panic(err)
	}
	return path
}
